package com.metroinfo.parser;

import java.nio.ByteBuffer;

import com.metroinfo.infrastructure.keys.StationInfoDataKey;
import com.metroinfo.parser.data.SendDataPar;


public class ParseSendData implements ParseInterface {

	final int MIN_LENGHT = 7;
	final int BASE_DATA = 6;
	final int ONE_PAR = 3;

	@Override
	public Object[] getParsed(ByteBuffer cb) {
		//System.out.println("Evo nas ovde");
		if (!isFormatCorrect(cb)) return null;
		
		int numberOfPars = cb.get(5);
		
		int stationID = cb.get(2) + 256 * cb.get(1);
		int stationTime = cb.get(4) + 256 * cb.get(3);
		
		SendDataPar[] retVal = new SendDataPar[numberOfPars];
		
		for(int i=0;i<numberOfPars; i++)
		{
			retVal[i] = new SendDataPar(stationID
					, cb.get(BASE_DATA+i*ONE_PAR+1) + 256 * cb.get(BASE_DATA+i*ONE_PAR) 
					, stationTime - cb.get(BASE_DATA+i*ONE_PAR+2));
		}

		return retVal;
	}

	@Override
	public boolean isFormatCorrect(ByteBuffer cb) {
		if (cb.limit()< MIN_LENGHT)
			return false;

		int numberOfPars = cb.get(5);
		if (numberOfPars * ONE_PAR + MIN_LENGHT != cb.limit())
			return false;
		
		if (cb.get(cb.limit()-1)!= 0) return false; 
		
		return true;
	}

	@Override
	public Object getKey(ByteBuffer bb) {
		if (!isFormatCorrect(bb)) return null;
		
		int stationID = bb.get(2) + 256 * bb.get(1);
		System.out.println("Kljuc je -"+stationID);
		return new StationInfoDataKey(Integer.valueOf(stationID));
	}

}
